import uvicorn
from fastapi import FastAPI, Request
from fastapi.responses import RedirectResponse
from fastapi.staticfiles import StaticFiles
from starlette.websockets import WebSocket, WebSocketDisconnect
from tortoise.contrib.fastapi import register_tortoise
from douyin.api import dy_app
from account.api import user_app
from settings import TORTOISE_ORM, websocket_connections
# from douyin import task_user
from models import *


# @asynccontextmanager
# async def lifespan(app: FastAPI):
#     js = "Object.defineProperties(navigator, {webdriver:{get:()=>undefined}});"
#     async with async_playwright() as pw:
#         browser = await pw.chromium.launch(headless=False)
#         context = await browser.new_context(
#             user_agent='Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36',
#             viewport={'width': 1366, 'height': 768})
#         await context.add_init_script(js)
#         task_user.start(context)
#         yield
    # 在这里放置关闭逻辑


app = FastAPI()

app.mount("/static", StaticFiles(directory="templates/static"), name="static")

app.include_router(dy_app, prefix="/douyin", tags=["抖音直播间任务控制"])
app.include_router(user_app, prefix='/account', tags=['用户管理'])

register_tortoise(
    app,
    config=TORTOISE_ORM
    # generate_schemas=True,  # 如果数据库为空，则自动生成对应表单，生产环境不要开
    # add_exception_handlers=True,  # 生产环境不要开，会泄露调试信息
)

# 中间件判断登录状态
@app.middleware("http")
async def check_login(request: Request, call_next):
    if request.url.path.startswith('/account') or request.url.path.startswith('/static') or request.url.path.startswith('/ws'):
        return await call_next(request)

    uid = request.cookies.get('uid')
    user = await User.get_or_none(uid=uid)
    if user is None:
        return RedirectResponse(url='/account/login')
    return await call_next(request)


@app.get('/')
async def home():
    return RedirectResponse("/douyin/task")


@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
    await websocket.accept()
    websocket_connections.append(websocket)
    try:
        while True:
            await websocket.receive_text()
            # await websocket.send_text(f"Message received: {data}")
    except WebSocketDisconnect:
        websocket_connections.remove(websocket)
        print("Client disconnected")


if __name__ == '__main__':
    uvicorn.run("main:app", host="127.0.0.1", port=8080, reload=False)
